package com.example.demo.keyresolver.impl;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.crypto.SecureUtil;
import com.example.demo.annotation.Idempotent;
import com.example.demo.keyresolver.IdempotentKeyResolver;
import com.example.demo.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.core.ParameterNameDiscoverer;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * 基于 Spring EL 表达式，
 *
 * @author houp
 */
@Component
@Slf4j
public class ExpressionIdempotentKeyResolver implements IdempotentKeyResolver {

    private final ParameterNameDiscoverer parameterNameDiscoverer = new LocalVariableTableParameterNameDiscoverer();
    private final ExpressionParser expressionParser = new SpelExpressionParser();

    Map<String, Class<?>> parameterTypeMap = new HashMap<>();

    @Override
    public String resolver(HttpServletRequest request, JoinPoint joinPoint, Idempotent idempotent) {
        StringBuilder data = new StringBuilder();
        data.append(joinPoint.getSignature().toString());
        data.append(":");
        data.append(request.getMethod());
        data.append(":");
        // 获得被拦截方法参数名列表
        Method method = getMethod(joinPoint);
        Object[] args = joinPoint.getArgs();
        String[] parameterNames = this.parameterNameDiscoverer.getParameterNames(method);
        Class<?>[] parameterTypes = method.getParameterTypes();
        // 准备 Spring EL 表达式解析的上下文
        EvaluationContext evaluationContext = new StandardEvaluationContext();
        if (ArrayUtil.isNotEmpty(parameterNames)) {
            for (int i = 0; i < parameterNames.length; i++) {
                evaluationContext.setVariable(parameterNames[i], args[i]);
                parameterTypeMap.put(parameterNames[i], parameterTypes[i]);
            }
        }
        for (String keyArg : idempotent.keyArgs()) {
            // 解析参数
            Expression expression = expressionParser.parseExpression(keyArg);
            Object value = expression.getValue(evaluationContext, parameterTypeMap.get(keyArg));
            data.append(JsonUtils.toJson(value));
        }
        log.info("md5加密前数据: " + JsonUtils.toJson(data.toString()));
        String md5 = SecureUtil.md5(data.toString());
        return md5;
    }

    private static Method getMethod(JoinPoint point) {
        // 处理，声明在类上的情况
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        if (!method.getDeclaringClass().isInterface()) {
            return method;
        }
        // 处理，声明在接口上的情况
        try {
            return point.getTarget().getClass().getDeclaredMethod(point.getSignature().getName(), method.getParameterTypes());
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
    }

}
